package com.bruce.main.ui;

import android.app.Application;
import android.os.Build;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableList;

import com.bruce.main.BR;
import com.bruce.main.R;
import com.bruce.main.bean.SignBean;
import com.bruce.main.repository.SingRepository;
import com.bruce.main.utils.SignUtil;
import com.haibin.calendarview.Calendar;
import com.hjq.toast.ToastUtils;

import java.util.Comparator;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.binding.command.BindingConsumer;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.SPUtils;
import me.goldze.mvvmhabit.utils.TimeUtil;
import me.tatarka.bindingcollectionadapter2.ItemBinding;

public class ViewModel extends BaseViewModel {
    public ObservableField<String> monthDay = new ObservableField<>("");// 月+日
    public ObservableField<String> year = new ObservableField<>("");// 年
    public ObservableField<String> lunar = new ObservableField<>("");// 农历
    public ObservableField<String> countStr = new ObservableField<>("总记录条数：");
    public ObservableField<String> signDay = new ObservableField<>("打卡天数：");
    public ObservableField<String> continuousDay = new ObservableField<>("连续打卡天数：");
    public ObservableField<String> hisContinuousDay = new ObservableField<>("历史连续打卡天数：");
    public ObservableField<Boolean> enableLoadMore = new ObservableField<>(false);//是否可以加载更多
    private String dayStr;
    private Calendar calendar;//当前日期
    private List<SignBean> signBeans;// 分组后的签到数据
    long count;//总记录条数
    int continuousSignInDay;
    int hisContinuousSignInDay;//历史最高连续打卡天数

    public ViewModel(@NonNull Application application) {
        super(application);
    }

    public void init(Calendar calendar) {

        setDate(calendar);
        hisContinuousSignInDay=SPUtils.getInstance().getInt("hisContinuousSignInDay",0);
        hisContinuousDay.set("历史连续打卡天数："+hisContinuousSignInDay);
        this.calendar = calendar;
        getDataByDay(TimeUtil.getTimeFromMillisecond(calendar.getTimeInMillis()));
        queryCount();
//        queryCountDay();
        queryGroupByDay();
    }

    private void setDate(Calendar calendar) {
        //        少量字符串拼接就直接+了
        monthDay.set(calendar.getMonth() + "月" + calendar.getDay() + "日");
        year.set(String.valueOf(calendar.getYear()));
        lunar.set(calendar.getLunar());
    }

    //给RecyclerView添加ObservableList
    public ObservableList<ItemModel> observableList = new ObservableArrayList<>();
    //给RecyclerView添加ItemBinding
    public ItemBinding<ItemModel> itemBinding = ItemBinding.of(BR.viewModel, R.layout.item_sign);
    public UIChangeObservable uc = new UIChangeObservable();

    public void changeCalendar(Calendar calendar) {
        setDate(calendar);
    }

    //下拉刷新
    public BindingCommand onRefreshCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            page = 0;
            getDataByDay(dayStr);
        }
    });
    public BindingCommand onLoadMoreCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            page++;
            getDataByDay(dayStr);
        }
    });

    public class UIChangeObservable {
        // 改变日历的显示
        public SingleLiveEvent changeCalendarView = new SingleLiveEvent<>();
        // 改变选择的时间
        public SingleLiveEvent changeSelectDate = new SingleLiveEvent<>();
        public SingleLiveEvent refreshDone = new SingleLiveEvent<>();
    }

    public BindingCommand mothClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            uc.changeCalendarView.call();
        }
    });
    public BindingCommand signClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            signIn();
        }
    });

    public void deleteItem(ItemModel itemModel) {
        reMoveItem(itemModel);
    }


    public BindingCommand<Integer> onYearChange = new BindingCommand<Integer>(new BindingConsumer<Integer>() {
        @Override
        public void call(Integer newYear) {
            monthDay.set(String.valueOf(newYear));
        }
    });
    public BindingCommand<Calendar> onSelectDateChange = new BindingCommand<Calendar>(new BindingConsumer<Calendar>() {
        @Override
        public void call(Calendar calendar) {
            uc.changeSelectDate.call();
            page = 0;
            ViewModel.this.calendar = calendar;
            getDataByDay(TimeUtil.getTimeFromMillisecond(calendar.getTimeInMillis()));
        }
    });
    private int page = 0;
    private int pageSize = 10;

    /**
     * 获取当天的打卡数据
     *
     * @param day
     */
    private void getDataByDay(String day) {
        Log.e("bruce", "getDataByDay: >>>>>>>>>>>>>>>>>>>>" + day);
        dayStr = day;
        SingRepository.getInstance().queryByDay(this, day, page, pageSize, new Observer() {
            @Override
            public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {

            }

            @Override
            public void onNext(@io.reactivex.annotations.NonNull Object o) {
                List<SignBean> signBeans = (List<SignBean>) o;
                uc.refreshDone.call();
                if (page == 0) {
                    observableList.clear();
                }
                enableLoadMore.set(signBeans.size() >= pageSize);
                for (SignBean signBean : signBeans) {
                    ItemModel itemDialogViewModel = new ItemModel(ViewModel.this, signBean);
                    observableList.add(itemDialogViewModel);
                }
            }

            @Override
            public void onError(@io.reactivex.annotations.NonNull Throwable e) {
                ToastUtils.show(e.getMessage());
            }

            @Override
            public void onComplete() {

            }
        });
    }

    /**
     * 打卡
     */
    private void signIn() {

        SingRepository.getInstance().insertSign(this, calendar.getTimeInMillis(), new Observer() {
            @Override
            public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {

            }

            @Override
            public void onNext(@io.reactivex.annotations.NonNull Object o) {
                SignBean signBean = (SignBean) o;
                ItemModel itemDialogViewModel = new ItemModel(ViewModel.this, signBean);
                observableList.add(itemDialogViewModel);
                ToastUtils.show("签到成功");
                count++;
                countStr.set("总记录条数：" + count);
                queryGroupByDay();
            }

            @Override
            public void onError(@io.reactivex.annotations.NonNull Throwable e) {
                ToastUtils.show(e.getMessage());
            }

            @Override
            public void onComplete() {

            }
        });
    }

    /**
     * 删除一条打卡记录
     *
     * @param itemModel
     */
    private void reMoveItem(ItemModel itemModel) {
        SingRepository.getInstance().deleteById(this, itemModel.bean.get().getId(), new Observer() {
            @Override
            public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {

            }

            @Override
            public void onNext(@io.reactivex.annotations.NonNull Object o) {
                observableList.remove(itemModel);
                if (count > 0) {
                    count--;
                    countStr.set("总记录条数：" + count);
                }
                queryGroupByDay();
            }

            @Override
            public void onError(@io.reactivex.annotations.NonNull Throwable e) {
                ToastUtils.show(e.getMessage());
            }

            @Override
            public void onComplete() {

            }
        });

    }

    /**
     * 查询总记录条数
     */
    private void queryCount() {
        SingRepository.getInstance().queryCount(this, new Observer() {
            @Override
            public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {

            }

            @Override
            public void onNext(@io.reactivex.annotations.NonNull Object o) {
//                observableList.remove(itemModel);
                count = (long) o;
                countStr.set("总记录条数：" + count);
            }

            @Override
            public void onError(@io.reactivex.annotations.NonNull Throwable e) {
                ToastUtils.show(e.getMessage());
            }

            @Override
            public void onComplete() {

            }
        });

    }

    /**
     * 分组获取数据
     */
    private void queryGroupByDay() {
        SingRepository.getInstance().queryGroupByDay(this, new Observer() {
            @Override
            public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {

            }

            @Override
            public void onNext(@io.reactivex.annotations.NonNull Object o) {
//                observableList.remove(itemModel);
                signBeans = (List<SignBean>) o;
                signDay.set("打卡天数：" + signBeans.size());
//                根据时间排序
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    signBeans.sort(new Comparator<SignBean>() {
                        @Override
                        public int compare(SignBean o1, SignBean o2) {
                            return (int) (o1.getTime() - o2.getTime());
                        }
                    });
                }
                getContinuousSignInDay(signBeans);
            }

            @Override
            public void onError(@io.reactivex.annotations.NonNull Throwable e) {
                ToastUtils.show(e.getMessage());
            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void getContinuousSignInDay(List<SignBean> signBeans) {

        Integer[] integers = new Integer[signBeans.size()];
        for (int i = 0; i < signBeans.size(); i++) {
            SignBean signBean = signBeans.get(i);
            String replace = signBean.getDayStr().replace("-", "");
            integers[i] = Integer.parseInt(replace);
            Log.e("bruce", "onNext: >>>>>>>>>signBeans>>>>>>>>>>>" + integers[i]);
        }
        int max = 0;
        for (int i = 0; i < integers.length; i++) {
            int temp = 1;
            Log.e("bruce", " >>>>>>>>>>>>>>>>>>>>" + integers[i]);
            for (int j = i + 1; j < integers.length; j++) {
                if (integers[j] - integers[i] == j - i) {
                    temp = j - i;
                    Log.e("bruce", " >>>>>>>>>>>>>>>>>>>>" + integers[j]);
                } else {
                    break;
                }
                if (temp > max) {
                    max = temp;
                }
            }
            Log.e("bruce", " >>>>>>>>>>>>>>>>>>>>");
        }

        continuousSignInDay = max + 1;
        if(continuousSignInDay>hisContinuousSignInDay){
            hisContinuousSignInDay=continuousSignInDay;
            SPUtils.getInstance().put("hisContinuousSignInDay",hisContinuousSignInDay);
            hisContinuousDay.set("历史连续打卡天数："+hisContinuousSignInDay);
        }
        continuousDay.set("连续打卡天数："+continuousSignInDay);
    }
}
